#include "VSession.h"
#include "ui_VSession.h"
#include "AbsConnection.h"
#include <QSplitter>
#include "CMainWindow.h"
#include "VCharts.h"
#include "VToast.h"
#include <QDebug>
#include <QUuid>
#include "CHelper.h"
#include "CTableQuick.h"
#include "CTableTrigger.h"
#include "CTableConfig.h"

VSession::VSession(QString strId, QWidget *parent) :
    VBaseSplitterForm(parent),
    ui(new Ui::VSession)
{
    ui->setupUi(this);

//    QTimer::singleShot(0,this,[=]{
        init(); //初始化会话连接及界面
        init(strId);
        CTableSession::instance()->updateColumn(m_stSession.id,CTableSession::active,true);
        qInfo()<<"显示会话";
//    });
}

VSession::~VSession()
{
    CTableSession::instance()->updateColumn(m_stSession.id,CTableSession::active,false);
    delete ui;
}

void VSession::init(QString strId)
{
    //新建
    if(strId.isEmpty()){
        m_stSession.id = CHelper::createUuid();
        m_stSession.s_is_hex = false;
        m_stSession.text_code = CTableConfig::instance()->queryValue(CTableConfig::TextCode);
        m_stSession.create_time = CHelper::currentDateTime();
        qDebug()<<"新建Session"<<m_stSession.id;
        CTableSession::instance()->addRow(m_stSession);
    }else{
        qDebug()<<"CTableSession 读取Session"<<strId;
        m_stSession = CTableSession::instance()->queryRow(strId);

        ui->widget_vconnect->ui->comboBox_protocal->setCurrentText(m_stSession.session_type);

        if(!m_stSession.ip.isEmpty()){
            ui->widget_vconnect->ui->comboBox_ip->setCurrentText(m_stSession.ip);
        }
        if(0 != m_stSession.port){
            ui->widget_vconnect->ui->comboBox_port->setCurrentText(QString::number(m_stSession.port));
        }


        ui->widget_vconnect->ui->comboBox_serial_name->setCurrentText(m_stSession.seial_name);
        ui->widget_vconnect->ui->comboBox_baudrate->setCurrentText(QString::number(m_stSession.baude));
        ui->widget_vconnect->ui->comboBox_data_bit->setCurrentText(QString::number(m_stSession.data_bit));
        ui->widget_vconnect->ui->comboBox_parity->setCurrentText(m_stSession.parity);
        ui->widget_vconnect->ui->comboBox_stop_bit->setCurrentText(m_stSession.stop_bit);
        ui->widget_vconnect->ui->comboBox_flowctrl->setCurrentText(m_stSession.flowctrl);


        ui->widget_vreceive->ui->textEdit_receive->setPlainText(m_stSession.r_text_url);
        ui->widget_vreceive->ui->pushButton_hex->setChecked(m_stSession.r_is_hex);
        ui->widget_vreceive->ui->pushButton_display_send->setChecked(m_stSession.r_show_send);
        ui->widget_vreceive->ui->pushButton_timestamp->setChecked(m_stSession.r_show_timestamp);
        ui->widget_vreceive->ui->pushButton_stop->setChecked(!m_stSession.r_start);

        ui->widget_vsend->ui->textEdit_send->setPlainText(m_stSession.s_text_url);
        ui->widget_vsend->ui->pushButton_hex->setChecked(m_stSession.s_is_hex);
        ui->widget_vsend->ui->spinBox_auto_span->setValue(m_stSession.s_auto_span);

//        ui->widget_vsend->ui->checkBox_quick_hex->setChecked(m_stSession.s_is_hex);
//        ui->widget_vsend->ui->spinBox_quick_span->setValue(m_stSession.s_auto_span);
        ui->widget_vsend->clearQuickSend();
        QVector<StQuick> vecData = CTableQuick::instance()->queryRows(m_stSession.id);
        foreach (StQuick item, vecData) {
            ui->widget_vsend->appendQuickSend(StQuickSend(item.text,item.is_hex,item.span));
        }

//        ui->widget_vsend->ui->checkBox_trig_hex->setChecked(m_stSession.send.trig.hex_enable);
//        ui->widget_vsend->ui->pushButton_trig_start->setChecked(m_stSession.send.trig.start_enable);
//        ui->widget_vsend->clearTrig();
//        foreach (CTrigItemData item, m_stSession.send.trig.trig_items) {
//            ui->widget_vsend->appendTrig(StReceiveTrig(item.trig_text,item.reply_text,item.hex_enable));
//        }
    }

    if(!m_stSession.s_is_hex){
        ui->widget_vsend->setTextCode(m_stSession.text_code);
    }else{
        ui->widget_vsend->on_pushButton_hex_clicked(true);
    }
}

void VSession::setFormChecked(bool bIsChecked)
{
    m_bChecked = bIsChecked;
    if(m_bChecked){
        //刷新状态栏的计数
        CMainWindow::getInstance()->slotRecvBytes(m_pConnectManager->recvBytes());
        CMainWindow::getInstance()->slotSendBytes(m_pConnectManager->sendBytes());
    }

    ui->frame_session->setProperty("selected",m_bChecked);              //通过属性修改选中框颜色
    ui->frame_session->setStyleSheet(ui->frame_session->styleSheet());  //状态变化 刷新样式
}

bool VSession::isChecked()
{
    return m_bChecked;
}

void VSession::init()
{
    ui->splitter->setStretchFactor(0, 2); //设置窗口分割比例 接收占2
    ui->splitter->setStretchFactor(1, 1); //发送占1

    m_pConnectManager = new CConnectManager(this);

    ui->widget_vconnect->setConnectionProxy(m_pConnectManager);
    ui->widget_vreceive->setConnectionProxy(m_pConnectManager);
    ui->widget_vsend->setConnectionProxy(m_pConnectManager);

    m_pConnectManager->resetConnect(AbsConnection::ENM_TCP_CLIENT);

    setFormChecked(false); //默认边框

    //收发计数
    connect(m_pConnectManager,&CConnectManager::sigSendBytes,[=](int nBytes){
        if(m_bChecked){
            CMainWindow::getInstance()->slotSendBytes(nBytes);
        }
    });
    connect(m_pConnectManager,&CConnectManager::sigRecvBytes,[=](int nBytes){
        if(m_bChecked){
            CMainWindow::getInstance()->slotRecvBytes(nBytes);
        }
    });
    connect(CMainWindow::getInstance(),&CMainWindow::sigRecount,[=]{
        if(m_bChecked){
            m_pConnectManager->slotRecount();
        }
    });
}

void VSession::showChartSetting(bool bShow)
{
    Q_UNUSED(bShow)
    ui->widget_vreceive->ui->chart->clickedMore();
}

QString VSession::id()
{
    return m_stSession.id;
}

QString &VSession::name()
{
    return m_stSession.name;
}

bool VSession::setTextCode(QString strTextCode)
{
    bool ok = CTableSession::instance()->updateColumn(id(),CTableSession::text_code,strTextCode);
    if(ok){
        m_stSession.text_code = strTextCode;

        ui->widget_vsend->setTextCode(strTextCode);
        emit textCodeChanged(strTextCode);
    }
    return ok;
}

void VSession::saveSession()
{
    m_stSession.active           = isChecked();
//    m_stSession.create_time      =
//    m_stSession.close_time       =
//    m_stSession.using_time       =
//    m_stSession.text_code        =
    m_stSession.session_type     = ui->widget_vconnect->ui->comboBox_protocal->currentText();
    m_stSession.ip               = ui->widget_vconnect->ui->comboBox_ip->currentText();
    m_stSession.port             = ui->widget_vconnect->ui->comboBox_port->currentText().toUInt();
    m_stSession.seial_name       = ui->widget_vconnect->ui->comboBox_serial_name->currentText();
    m_stSession.baude            = ui->widget_vconnect->ui->comboBox_baudrate->currentText().toInt();
    m_stSession.data_bit         = ui->widget_vconnect->ui->comboBox_data_bit->currentText().toInt();
    m_stSession.parity           = ui->widget_vconnect->ui->comboBox_parity->currentText();
    m_stSession.stop_bit         = ui->widget_vconnect->ui->comboBox_stop_bit->currentText();
    m_stSession.flowctrl         = ui->widget_vconnect->ui->comboBox_flowctrl->currentText();
    m_stSession.r_text_url       = ui->widget_vreceive->ui->textEdit_receive->toPlainText(); //可能是超大文本
    m_stSession.r_is_hex         = ui->widget_vreceive->ui->pushButton_hex->isChecked();
    m_stSession.r_show_send      = ui->widget_vreceive->ui->pushButton_display_send->isChecked();
    m_stSession.r_show_timestamp = ui->widget_vreceive->ui->pushButton_timestamp->isChecked();
    m_stSession.r_start          = !ui->widget_vreceive->ui->pushButton_stop->isChecked();
    m_stSession.s_text_url       = ui->widget_vsend->ui->textEdit_send->toPlainText(); //可能是大文本
    m_stSession.s_is_hex         = ui->widget_vsend->ui->pushButton_hex->isChecked();
    m_stSession.s_auto_enable    = ui->widget_vsend->ui->checkBox_auto_send->isChecked();
    m_stSession.s_auto_span      = ui->widget_vsend->ui->spinBox_auto_span->value();

//    ui->widget_vsend->ui->checkBox_quick_hex->isChecked();
//    ui->widget_vsend->ui->spinBox_quick_span->value();

    //快捷发送
    QVector<StQuick> vecData;
    foreach (VQuickSend *pQuickSend, ui->widget_vsend->m_vecQuickSend) {
        StQuick item;
        item.id = CHelper::createUuid();
        item.session_id = m_stSession.id;
        item.is_hex = pQuickSend->info().bHex;
        item.span = pQuickSend->info().nSpan;
        item.text = pQuickSend->info().strText;
        vecData.append(item);
    }

    CTableQuick::instance()->deleteSession(m_stSession.id);
    CTableQuick::instance()->addRows(vecData);


//    ui->widget_vsend->ui->checkBox_trig_hex->isChecked();
//    ui->widget_vsend->ui->pushButton_trig_start->isChecked();

    //触发器
    QVector<StTrigger> vecTriggers;
    foreach (VReceiveTrig *pItem, ui->widget_vsend->m_vecReceiveTrig) {
        StTrigger item;
        item.id = CHelper::createUuid();
        item.session_id = m_stSession.id;
        item.conditions = pItem->info().strRText;
        item.reply = pItem->info().strSText;
        item.is_hex = pItem->info().bHex;

        vecTriggers.append(item);
    }
    CTableTrigger::instance()->deleteSession(m_stSession.id);
    CTableTrigger::instance()->addRows(vecTriggers);

    if(CTableSession::instance()->updateRow(m_stSession))
        VToast::getInstance()->show(tr("已保存成功!"));
    else
        VToast::getInstance()->show(tr("保存失败!"));
}

void VSession::closeSession()
{
    CTableSession::instance()->updateColumn(id(),CTableSession::close_time,CHelper::currentDateTime());
}

void VSession::removeSession()
{
    CTableSession::instance()->deleteRow(m_stSession.id);
}
